/**
 * 
 */
package de.wesemann.mediahandbook.le.activity;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import de.wesemann.jdedun.entities.mediahandbook.branches.MediahandbookBranche;
import de.wesemann.jdedun.entities.mediahandbook.companies.MediahandbookCompany;
import de.wesemann.jdedun.entities.mediahandbook.people.MediahandbookPeople;
import de.wesemann.mediahandbook.le.R;
import de.wesemann.mediahandbook.le.activity.helper.AbstractActivity;
import de.wesemann.mediahandbook.le.activity.helper.AbstractAsyncTask;
import de.wesemann.mediahandbook.le.adapter.CompanyAdapter;
import de.wesemann.mediahandbook.le.adapter.ExpListAdapCompanyDetail;
import de.wesemann.mediahandbook.le.util.BranchUtil;
import de.wesemann.mediahandbook.le.util.DistrictUtil;
import de.wesemann.mediahandbook.le.util.PeopleUtil;
import de.wesemann.mediahandbook.le.widget.TitleWidget;

/**
 * @author spinner0815
 * 
 */
public class CompanyDetail extends AbstractActivity {
	private static final String LOG_TAG = CompanyDetail.class.getSimpleName();
	private MediahandbookCompany mCompany;
	private ExpandableListView mEpViewAccessable;
	// private ProgressDialog progress;
	// private List<MediahandbookPeople> mPeoples;
	// private String[] mBranch;
	// private ProgressDialog mProgress;
	// private String mDistrictName;
	private TitleWidget titleWidget;

	private static enum TAGS {
		BRANCH, PEOPLE, DISTRICTS
	}

	private HashMap<TAGS, List<?>> mResources = new HashMap<CompanyDetail.TAGS, List<?>>();

	private ListView mLvCompanyDetails;
	private LoadItems mTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.companies_detail);

		setUpTitleWidget();

		// mProgress = new ProgressDialog(this);
		final Bundle extras = getIntent().getExtras();
		mCompany = (MediahandbookCompany) extras.get("MediahandbookCompany");
		Log.d(LOG_TAG, mCompany.toString());
		final List<MediahandbookCompany> mediaComps = new ArrayList<MediahandbookCompany>();
		mediaComps.add(mCompany);
		mLvCompanyDetails = (ListView) findViewById(R.id.lv_cd_detail);
		ListView lvAddress = (ListView) findViewById(R.id.lv_cd_address);
		CompanyAdapter mComAdap = new CompanyAdapter(this, mediaComps);
		lvAddress.setAdapter(mComAdap);
		registerForContextMenu();
		Object retained = getLastNonConfigurationInstance();
		if (retained instanceof LoadItems) {
			mTask = (LoadItems) retained;
			mTask.setActivity(this);
		} else {
			mTask = new LoadItems(this);
			mTask.execute();

		}

	}

	private void setUpTitleWidget() {
		titleWidget = (TitleWidget) findViewById(R.id.co_titleWidget);
		titleWidget.setTitle(getString(R.string.company_details));
		titleWidget.setLeftIcon(R.drawable.bu_house_conf);
		titleWidget.hideSearchIcon();
		titleWidget.hideProgressBar();
	}

	private void createCompanyDetailList() {

		String KEY_LABEL = "label";
		String KEY_HELP = "help";
		HashMap<String, String> elements;
		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		elements = new HashMap<String, String>();
		elements.put(KEY_LABEL, getString(R.string.company_district));
		if (mResources.get(TAGS.DISTRICTS) != null && mResources.get(TAGS.DISTRICTS).size() > 0) {
			elements.put(KEY_HELP, (String) mResources.get(TAGS.DISTRICTS).get(0));
		}
		list.add(elements);

		mLvCompanyDetails.setAdapter(new SimpleAdapter(this, list, R.layout.company_detail_row, new String[] {
				KEY_LABEL, KEY_HELP }, new int[] { R.id.tv_cd_lv_key, R.id.tv_cd_lv_value }));
	}

	private void registerForContextMenu() {
		registerForContextMenu(findViewById(R.id.lv_cd_address));
		registerForContextMenu(findViewById(R.id.lv_cd_detail));
		registerForContextMenu(findViewById(R.id.elv_cd_details));
	}

	@SuppressWarnings("unchecked")
	private void createExpandableView() {
		mEpViewAccessable = (ExpandableListView) findViewById(R.id.elv_cd_details);
		mEpViewAccessable.setAdapter(new ExpListAdapCompanyDetail(this, mCompany,
				(List<MediahandbookPeople>) mResources.get(TAGS.PEOPLE), (List<MediahandbookBranche>) mResources
						.get(TAGS.BRANCH)));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		Intent intent = null;
		if (item.getItemId() == R.id.men_show_in_map) {
			StringBuilder sb = new StringBuilder();
			sb.append(mCompany.getStreet().replaceAll(" ", "%20")).append("%20").append(mCompany.getHousenumber())
					.append(",%20").append(mCompany.getPostcode().trim()).append("%20")
					.append(mCompany.getCity().trim().replaceAll(" ", "%20"));
			Log.d(LOG_TAG, sb.toString());
			intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + sb.toString()));
			try {
				startActivity(intent);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(this, getString(R.string.activity_not_found) + getString(R.string.show_on_map),
						Toast.LENGTH_SHORT).show();
			}
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.lv_cd_address) {
			getMenuInflater().inflate(R.menu.companydetail_adress_context, menu);
		} else if (v.getId() == R.id.lv_cd_detail) {
			// AdapterView.AdapterContextMenuInfo info =
			// (AdapterView.AdapterContextMenuInfo) menuInfo;
			// Log.d(LOG_TAG, "LONG: " + info.position);
			//
			// ListView lv = (ListView) findViewById(R.id.lv_cd_detail);
			//
			// @SuppressWarnings("unchecked")
			// HashMap<String, String> content = (HashMap<String, String>) lv
			// .getItemAtPosition(info.position);
			// if (content.get("label").contains(
			// getString(R.string.company_branch))) {
			// getMenuInflater().inflate(
			// R.menu.companydetail_branches_context, menu);
			// } else if (content.get("label").contains(
			// getString(R.string.company_district))) {
			// getMenuInflater().inflate(
			// R.menu.companydetail_district_context, menu);
			// }
		} else if (v.getId() == R.id.elv_cd_details) {
			createExpListContextmenu(menuInfo);
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	private void createExpListContextmenu(ContextMenuInfo menuInfo) {
		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		int group = ExpandableListView.getPackedPositionGroup(info.packedPosition);
		int child = ExpandableListView.getPackedPositionChild(info.packedPosition);
		Log.d(LOG_TAG, "type:" + type + " group: " + group + " child: " + child);
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {

			ExpListAdapCompanyDetail expAdap = (ExpListAdapCompanyDetail) mEpViewAccessable.getExpandableListAdapter();
			String title = expAdap.getChildContent(group, child);
			String key = expAdap.getChildKeyContent(group, child);
			if (key.contains(getString(R.string.url_primary)) || key.contains(getString(R.string.url_secondary))) {

				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(title));
				try {
					startActivity(intent);
				} catch (ActivityNotFoundException e) {
					Toast.makeText(this, getString(R.string.activity_not_found) + getString(R.string.dial),
							Toast.LENGTH_SHORT).show();
				}
			} else if (key.contains(getString(R.string.phone_primary))
					|| key.contains(getString(R.string.phone_secondary))
					|| key.contains(getString(R.string.mobile_primary))
					|| key.contains(getString(R.string.mobile_secondary))) {

				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + title));
				try {
					startActivity(intent);
				} catch (ActivityNotFoundException e) {
					Toast.makeText(this, getString(R.string.activity_not_found) + getString(R.string.dial),
							Toast.LENGTH_SHORT).show();
				}
			} else if (key.contains(getString(R.string.email_primary))
					|| key.contains(getString(R.string.email_secondary))) {
				Intent emailIntent = new Intent(Intent.ACTION_SEND);
				emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { title });
				Log.d(LOG_TAG, title);
				emailIntent.setType("plain/text");
				try {
					startActivity(emailIntent);
				} catch (ActivityNotFoundException e) {
					Toast.makeText(this, getString(R.string.activity_not_found) + getString(R.string.email_send),
							Toast.LENGTH_SHORT).show();
				}
			} else if (group == 1) {
				// Intent intent = new Intent(Intent.ACTION_INSERT);
				// intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
				// // Just two examples of information you can send to pre-fill
				// out
				// // data for the
				// // user. See android.provider.ContactsContract.Intents.Insert
				// // for the complete
				// // list.
				//
				// intent.putExtra(ContactsContract.Intents.Insert.NAME,
				// title.substring(title.lastIndexOf(": ") + 2));
				// intent.putExtra(ContactsContract.Intents.Insert.PHONE,
				// "some Phone Number");
				// intent.putExtra(ContactsContract.Intents.Insert.EMAIL,
				// "some Email");
				// startActivity(intent);
			}
			Log.d(LOG_TAG, title);
		}
	}

	@Override
	public void reload(AbstractAsyncTask<?, ?, ?> task) {
		dismissDialog(LOADING_DIALOG);
//		Toast.makeText(this, getString(R.string.error_while_loading), Toast.LENGTH_LONG).show();
		if (task.getreLoadTries() < 3) {
			if (task instanceof LoadItems) {
				this.mTask.execute();
			}
		}

	}

	@Override
	public void onTaskCompleted(AbstractAsyncTask<?, ?, ?> task) {
		try {
			mResources = mTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		createCompanyDetailList();
		createExpandableView();
		if (mShownDialog) {
			dismissDialog(LOADING_DIALOG);
			Toast.makeText(this, getString(R.string.finished), Toast.LENGTH_LONG).show();
		}

	}

	/**
	 * After a screen orientation change, this method is invoked. As we're going
	 * to state save the task, we can no longer associate it with the Activity
	 * that is going to be destroyed here.
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		if (mTask != null) {
			Log.d(LOG_TAG, "Save the LoadItemsTask");
			mTask.setActivity(null);
			return mTask;
		}
		return null;

	}

	private class LoadItems extends AbstractAsyncTask<Void, Integer, HashMap<TAGS, List<?>>> {

		protected LoadItems(CompanyDetail activity) {
			super(activity);
		}

		int myProgress;
		private ArrayList<MediahandbookBranche> branches = new ArrayList<MediahandbookBranche>();
		private List<MediahandbookBranche> locBranches = new ArrayList<MediahandbookBranche>();
		private HashMap<TAGS, List<?>> resources = new HashMap<CompanyDetail.TAGS, List<?>>();

		@Override
		protected HashMap<TAGS, List<?>> doInBackground(Void... params) {

			publishProgress(myProgress);
			try {
				if (Integer.valueOf(mCompany.getSub_market_id()) != null) {
					Log.d(LOG_TAG, "The branch has the id " + mCompany.getSub_market_id());
					locBranches = BranchUtil.searchBranchById(mCompany.getSub_market_id());
					if (locBranches != null && locBranches.size() > 0) {
						this.branches.addAll(locBranches);
					}
					locBranches.clear();

				}
				if (Integer.valueOf(mCompany.getMain_branch_id()) != null) {
					locBranches = BranchUtil.searchBranchById(mCompany.getMain_branch_id());
					if (locBranches != null && locBranches.size() > 0) {
						this.branches.addAll(locBranches);
					}
					locBranches.clear();

				}
				if (mCompany.getSub_branches() != null && !mCompany.getSub_branches().isEmpty()) {
					locBranches = BranchUtil.searchBranchById(mCompany.getSub_branches());
					if (locBranches != null && locBranches.size() > 0) {
						this.branches.addAll(locBranches);
					}
					locBranches.clear();
				}
			} catch (FileNotFoundException e) {
				Log.e(LOG_TAG, "Error while loading " + e.getMessage());
				Toast.makeText(CompanyDetail.this, getString(R.string.error_while_loading), Toast.LENGTH_LONG).show();
			}
			// mBranch = new String[branches.size()];
			resources.put(TAGS.BRANCH, branches);
			myProgress = 25;
			publishProgress(myProgress);
			if (mCompany.getPeople() != null && !mCompany.getPeople().isEmpty()) {
				resources.put(TAGS.PEOPLE, PeopleUtil.getPeople(mCompany.getPeople()));
				// Log.d(LOG_TAG, "size of peoples: " + mPeoples.size());
			}
			myProgress = 50;
			publishProgress(myProgress);
			ArrayList<String> districtName = new ArrayList<String>();
			if (mCompany.getPostcode() == null || mCompany.getPostcode().equalsIgnoreCase("0")) {
				districtName.add((R.string.district_not_found) + mCompany.getPostcode());
			} else {
				int districtId = DistrictUtil.getDistrictIdByPostcode(mCompany.getPostcode());
				if (districtId != -1) {
					myProgress = 75;
					publishProgress(myProgress);
					districtName.add(DistrictUtil.getDistrictById(Integer.valueOf(districtId)).getName());
				}
			}
			resources.put(TAGS.DISTRICTS, districtName);
			myProgress = 100;
			publishProgress(myProgress);
			return resources;
		}

		@Override
		protected void onPreExecute() {
			Log.d(LOG_TAG, "PRE Executing");
			activity.showDialog(LOADING_DIALOG);
			myProgress = 0;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// mProgress.setProgress(values[0]);
		}
	}

	@Override
	protected void onDestroy() {
		Log.d(LOG_TAG, "onDestroy()");
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		Log.d(LOG_TAG, "onPause()");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		Log.d(LOG_TAG, "onRestart()");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		Log.d(LOG_TAG, "onResume()");
		super.onResume();
	}

	@Override
	protected void onStop() {
		Log.d(LOG_TAG, "onStop()");
		super.onStop();
	}

	@Override
	public void finish() {
		Log.d(LOG_TAG, "finish()");

		super.finish();
	}

}
